package com.cy.ragbase.controller;


import com.cy.ragbase.dto.*;
import com.cy.ragbase.entity.Document;
import com.cy.ragbase.service.DocumentService;
import com.cy.ragbase.service.RedisQueueService;
import com.cy.ragbase.service.SearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequiredArgsConstructor
@Slf4j
public class RagController {

    private final DocumentService documentService;
    private final SearchService searchService;
    private final RedisQueueService redisQueueService;

    /**
     * 上传文档
     */
    @PostMapping("/documents/upload")
    public ResponseEntity<DocumentUploadResponse> uploadDocument(
            @RequestParam("file") MultipartFile file) {

        try {

            Document document = documentService.uploadDocument(file);
            DocumentUploadResponse response = new DocumentUploadResponse();
            response.setDocumentId(document.getId());
            response.setFileName(document.getFileName());
            response.setStatus(document.getStatus());
            response.setMessage("Document uploaded successfully and queued for processing");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Failed to upload document", e);

            DocumentUploadResponse response = new DocumentUploadResponse();
            response.setStatus("FAILED");
            response.setMessage("Failed to upload document: " + e.getMessage());

            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取文档信息
     */
    @GetMapping("/documents/{documentId}")
    public ResponseEntity<Document> getDocument(@PathVariable String documentId) {
        try {
            Document document = documentService.getDocument(documentId);

            if (document == null) {
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok(document);

        } catch (Exception e) {
            log.error("Failed to get document: {}", documentId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除文档
     */
    @DeleteMapping("/documents/{documentId}")
    public ResponseEntity<Void> deleteDocument(@PathVariable String documentId) {
        try {
            documentService.deleteDocument(documentId);
            return ResponseEntity.ok().build();

        } catch (Exception e) {
            log.error("Failed to delete document: {}", documentId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 搜索文档
     */
    @PostMapping("/search")
    public ResponseEntity<SearchResponse> searchDocuments( @RequestBody SearchRequest request) {
        try {
            SearchResponse response = searchService.searchDocuments(request);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Search failed for query: {}", request.getQuery(), e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 混合搜索
     */
    @PostMapping("/search/hybrid")
    public ResponseEntity<SearchResponse> hybridSearch( @RequestBody SearchRequest request) {
        try {
            SearchResponse response = searchService.hybridSearch(request);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Hybrid search failed for query: {}", request.getQuery(), e);
            return ResponseEntity.internalServerError().build();
        }
    }


    /**
     * 获取任务状态
     */
    @GetMapping("/tasks/{taskId}/status")
    public ResponseEntity<TaskStatusResponse> getTaskStatus(@PathVariable String taskId) {
        try {
            String status = redisQueueService.getTaskStatus(taskId);
            String error = redisQueueService.getTaskError(taskId);

            TaskStatusResponse response = new TaskStatusResponse();
            response.setTaskId(taskId);
            response.setStatus(status != null ? status : "NOT_FOUND");
            response.setErrorMessage(error);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Failed to get task status: {}", taskId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<HealthResponse> health() {
        HealthResponse response = new HealthResponse();
        response.setStatus("UP");
        response.setMessage("RAG System is running");
        response.setTimestamp(System.currentTimeMillis());

        return ResponseEntity.ok(response);
    }


    /**
     * RAG提示词生成接口
     * 根据用户问题检索相关文档并生成适合大模型的提示词
     */
    @PostMapping("/rag/prompt")
    public ResponseEntity<RagPromptResponse> generateRagPrompt(@RequestBody RagPromptRequest request) {
        try {
            RagPromptResponse response = searchService.generateRagPrompt(request);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("RAG prompt generation failed for question: {}", request.getQuestion(), e);
            return ResponseEntity.internalServerError().build();
        }
    }

}


